import { numbers2Hex } from 'utils';
import { Sensor, SensorDataSet } from 'store';

const sensorSort = (a: Sensor, b: Sensor) =>
  (a.channel2.sequenceNumber || 0) - (b.channel2.sequenceNumber || 0);

export const onSetSensorSerialNumber = (
  sensors: Sensor[],
  {
    uint8T,
    channelNumber,
    sequenceNumber,
  }: SensorDataSet,
) => {
  if (![2, 3].includes(channelNumber)) {
    return sensors;
  }

  const serialNumber = numbers2Hex(uint8T);
  const isChannel2 = channelNumber === 2;
  const result = [...sensors];

  const sensor = result.find(
    (sensor) => sensor.serialNumber === serialNumber
  );

  // Серийник не приходил, тогда добавить новую запись
  if (!sensor) {
    const newSensor: Sensor = {
      channel2: {
        sequenceNumber: isChannel2 ? sequenceNumber : null,
      },
      channel3: {
        sequenceNumber: !isChannel2 ? sequenceNumber : null,
      },
      serialNumber,
      history: [],
    };

    return [...result, newSensor].sort(sensorSort);
  }

  // Серийник уже прилетал
  if (isChannel2) {
    if (sensor.channel2.sequenceNumber === sequenceNumber) {
      return sensors;
    }

    sensor.channel2.sequenceNumber = sequenceNumber;
  } else {
    if (sensor.channel3.sequenceNumber === sequenceNumber) {
      return sensors;
    }

    sensor.channel3.sequenceNumber = sequenceNumber;
  }

  return result.sort(sensorSort);
};
